// Copyright (C) 2011 Theodor T-Xen Artemenkov
// HerzEngine



#include	<fcntl.h>
#include	<io.h>
#include	<malloc.h>
#include	<ctype.h>
#include	<string>

#include	"FileData.h"
#include	"FString.h"


bool FileData::isAscii () const
{
	for ( int i = 0; i < length; i++ )
	{
		unsigned	ch = (unsigned) bits [i];

											// all chars ASCII are ok
		if ( ch >= 32 && ch < 128 )
			continue;

		if ( ch == '\n' || ch == '\r' || ch == '\t' )
			continue;

		if ( isalpha ( ch ) )					// check for locale characters
			continue;

		return false;
	}

	return true;
}

int	FileData::getBytes ( void * ptr, int len )
{
	if ( pos >= length )
		return -1;

	if ( pos + len > length )
		len = length - pos;

	memcpy ( ptr, bits + pos, len );
	pos += len;
	return len;
}

bool FileData::getString ( FString& str )
{
	char	buf [256];
	int		i = 0;

	str = "";

	if (pos >= length)
		return false;

	for ( ; pos < length && bits [pos] != '\n' && bits [pos] != '\0'; pos++ )
	{
		buf [i++] = bits [pos];

		if ( i >= sizeof ( buf ) - 1 )			// overflow
		{
			buf [i] = '\0';

			str += buf;

			i = 0;
		}
	}

	if ( pos < length && bits [pos] == '\n' )	// skip '\n'
		pos++;

	buf [i] = '\0';

	str += buf;

	return true;
}

FileData * FileData::getDataFromFile (const char * fileName)
{
	int	file = open (fileName, O_RDONLY | O_BINARY);

	if (file == -1)
		return NULL;

	long len = filelength ( file );

	if (len == -1)
	{
		close (file);
		return NULL;
	}

	char * buf = (char *) malloc ( len );

	if (buf == NULL)
	{
		close (file);
		return NULL;
	}

	FileData * data = new FileData ( fileName, buf, read (file, buf, len) );
	close (file);
	return data;
}
